# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import re
import hashlib

class ListBase(object):
    """列表解析"""
    ordersFirst = [
        '1',
        'a',
        'A',
        'i',
        'I'
    ]

    def __init__(self, content, paragraph_index, escape_char='\\'):
        super(ListBase, self).__init__()
        self.content = content
        self.cache_key = 'list'
        self.paragraph_index = paragraph_index
        self.escape_char = escape_char
        self.stack = []

    @staticmethod
    def isList(content):
        '''是否是列表'''
        _arr = content.split('\n')
        _list_pattern = r'^(\*|\.[0-9a-zA-Z]+\.)'
        for _line in _arr:
            if re.match(_list_pattern, _line):
                continue
            else:
                break
        else:
            return True
        return False

    def _ol_list_type(self, _order):
        return ''

    def parse(self):
        '''执行解析操作'''
        _arr = self.content.split('\n')
        _ol_pattern = r'^\.[0-9a-zA-Z]+\.'
        _ul_pattern = r'^\*+'
        _cache = []
        _stack = []
        _level = []
        for _line in _arr:
            _raw = _line
            if re.match(_ul_pattern, _line):
                _line = re.sub(_ul_pattern, '', _line)
            _len = len(_raw) - len(_line)
            if re.match(_ol_pattern, _line):
                _tag = 'ol'
                _tmp = re.sub(_ol_pattern, '', _line)
                _order = _line[:-len(_tmp)]
                if bool(_order) and len(_order) > 2:
                    _order = _order[1:-1]
                else:
                    raise Exception('ol list syntax error')
                _line = _tmp.strip()
                _type = self._ol_list_type(_order)
                _len += 1
            else:
                _tag = 'ul'
                _type = ''
            _real = _len
            if bool(_level):
                _deep = _level[-1]
            else:
                _deep = 0
            if _len > _deep:
                # deep +
                _stack.append(_tag)
                _level.append(_real)
                _stack.append('li')
                _cache.append('<{0}>'.format(_tag))
                _cache.append('<li>')
                _cache.append('<div>{0}</div>'.format(_line))
            else:
                if bool(_stack):
                    _cache.append('</{0}>'.format(_stack.pop()))
                if _len < _deep:
                    # deep -
                    while bool(_level):
                        _l = _level.pop()
                        if _l > _len:
                            if bool(_stack):
                                _t = _stack.pop()
                                if _t != 'li':
                                    _cache.append('</{0}>'.format(_t))
                                if bool(_stack):
                                    _cache.append('</{0}>'.format(_t))
                        else:
                            _level.append(_l)
                            break
                else:
                    #deep =
                    pass
                _stack.append('li')
                _cache.append('<li>')
                _cache.append('<div>{0}</div>'.format(_line))
        while bool(_stack):
            _cache.append('</{0}>'.format(_stack.pop()))
        
        _k = '@{0}_[{1}]'.format(
            self.cache_key,
            str(self.paragraph_index)
        )
        try:
            _k_md5 = hashlib.md5(_k).hexdigest()
        except Exception as ex:
            _k_md5 = hashlib.md5(_k.encode('utf-8', 'ignore')).hexdigest()
        _k = '{0}{{{1}}}'.format(
            '$',
            _k_md5
        )

        return {
            'content': _k,
            'cache': {
                _k: ''.join(_cache)
            }
        }

'''
*hello
**world
**hehe
**.1.dda
**.2.adf
*haha
*world
'''
'''
<ul>
    <li>
        hello
        <ul>
            <li>world</li>
            <li>
                hehe
                <ol>
                    <li>dda</li>
                    <li>adf</li>
                </ol>
            </li>
        </ul>    
    </li>
    <li>haha</li>
    <li>world</li>
</ul>
'''